package com.lw.leetcode.arr.c;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 2025. 分割数组的最多方案数
 *
 * @author liw
 * @version 1.0
 * @date 2023/2/3 15:19
 */
public class WaysToPartition {

    public static void main(String[] args) {
        WaysToPartition test = new WaysToPartition();

        // 1
//        int[] nums = {2, -1, 2};
//        int k = 3;

        // 2
//        int[] nums = {0, 0, 0};
//        int k = 1;

        // 1
//        int[] nums = {2, 1, 1, 1};
//        int k = 1;

        // 4
        int[] nums = {22, 4, -25, -20, -15, 15, -16, 7, 19, -10, 0, -13, -14};
        int k = -33;

        int i = test.waysToPartition(nums, k);
        System.out.println(i);
    }

    public int waysToPartition(int[] nums, int k) {
        Map<Long, Integer> map1 = new HashMap<>();
        Map<Long, Integer> map2 = new HashMap<>();
        int max = 0;
        long mid;
        long s1 = 0;
        long s2 = 0;
        for (int num : nums) {
            s1 += num;
            map1.merge(s1, 1, (a, b) -> a + b);
        }
        if ((s1 & 1) == 0) {
            max = map1.getOrDefault(s1 >> 1, 0);
            if (s1 == 0) {
                max--;
            }
        }
        for (int num : nums) {
            int c = k - num;
            long newSum = s1 + c;
            if ((newSum & 1) == 0) {
                mid = newSum >> 1;
                int t = map2.getOrDefault(mid, 0) + map1.getOrDefault(mid - c, 0);
                if(mid == 0) {
                    t--;
                }
                max = Math.max(max, t);
            }
            s2 += num;
            map1.put(s2, map1.get(s2) - 1);
            map2.merge(s2, 1, (a, b) -> a + b);
        }
        return max;
    }

}
